<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-createFiscalPeriod>
            <el-button
              v-if="$permission('fiscalPeriodSetting:setting')"
              :disabled="openInitDisabled"
              @click="createFiscalPeriod"
              >设置会计期间</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
      >
      </table-container>
    </div>
    <!--高级搜索-->
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!--偏好设置-->
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <page-dialog
      v-show="dateInfo.visible"
      :title="dateInfo.title"
      v-model:visible="dateInfo.visible"
      :width="dateInfo.width"
      :bt-loading="dateInfo.btLoading"
      :bt-list="dateInfo.btList"
      @reset="handleClose"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-initMonth>
          <el-date-picker
            v-model="formInfo.data.initMonth"
            type="month"
            value-format="YYYY-MM"
            format="YYYY-MM"
            placeholder="请选择月份"
            @change="changeMonth"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-startDate>
          <el-date-picker
            v-model="formInfo.data.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            placeholder="请选择开始日期"
            :disabled-date="formInfo.TimePickerOptions.disabledDate"
            :disabled="startDateDisable"
            @change="changeDate"
          >
          </el-date-picker>
        </template>
      </page-form>
    </page-dialog>
  </div>
</template>

<script setup name="fiscalPeriodSetting">
import TableContainer from "@/components/TableContainer/index";
import {
  creatBaseFiscalPeriod,
  getBaseFiscalPeriodEndDate,
  getBaseFiscalPeriodCustomizeListPage,
} from "@/api/base.js";
import { getCustomizeSetting, updateUserCustomize } from "@/api/customize";
import PageDialog from "@/components/PageDialog/index";
import moment from "moment";
import PageForm from "@/components/PageForm/index";
const SetPreference = defineAsyncComponent(() =>
  import("@/components/SetPreference/index")
);
const AdvancedSearch = defineAsyncComponent(() =>
  import("@/components/AdvancedSearch/index")
);

const { proxy } = getCurrentInstance();
// 过滤相关配置
const openInitDisabled = ref(false);
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: "button", label: "搜索", event: search },
    { type: "button", label: "高级查询", event: advancedSearchShow },
    { type: "button", label: "重置", event: clearSearch },
  ],
  btnList: [
    {
      label: "设置会计期间",
      type: "slot",
      value: "createFiscalPeriod",
    },
  ],
});
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
});
const advancedSearchInfo = ref({
  visible: false,
  data: {},
});
const preferenceInfo = ref({
  visible: false,
});
const clearType = ref(true);
const slipSelectRequest = ref(true);
const startDateDisable = ref(true);
const formInfo = ref({
  ref: null,
  ruleRef: null,
  data: {
    initMonth: "",
    startDate: "",
    endDate: "",
  },
  TimePickerOptions: {},
  fieldList: [
    {
      label: "月份",
      value: "initMonth",
      type: "slot",
    },
    {
      label: "开始日期",
      value: "startDate",
      type: "slot",
    },
    {
      label: "结束日期",
      value: "endDate",
      type: "date",
      disabled: true,
    },
  ],
  rules: {
    initMonth: [{ required: true, message: "请选择月份", trigger: "change" }],
    startDate: [
      { required: true, message: "请选择开始日期", trigger: "change" },
    ],
  },
  labelWidth: "120px",
});
const dateInfo = ref({
  visible: false,
  title: "选择起止日期",
  btLoading: false,
  type: "",
  msg: "",
  width: "40%",
  flag: true,
  btList: [
    { label: "关闭", event: handleClose, show: true },
    {
      label: "保存",
      type: "primary",
      event: save,
      show: true,
    },
  ],
});

setData();
function setData() {
  let obj = {
    year: {
      label: "名称",
      value: "year",
      componentType: "input",
      show: false,
      hidden: true,
    },
    name: {
      label: "会计期间",
      value: "name",
      componentType: "input",
      show: false,
      hidden: true,
    },
    startDate: {
      label: "开始日期",
      value: "startDate",
      componentType: "date",
      show: false,
      hidden: true,
    },
    endDate: {
      label: "结束日期",
      value: "endDate",
      componentType: "date",
      show: false,
      hidden: true,
    },
  };
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  getCustomize();
}

function changeMonth(val) {
  if (val) {
    startDateDisable.value = false;
    let startDate = moment(val)
      .subtract(1, "month")
      .startOf("month")
      .format("YYYY-MM-DD");
    let endDate = moment(val).endOf("month").format("YYYY-MM-DD");
    formInfo.value.TimePickerOptions = {
      disabledDate: (time) => {
        return (
          time.getTime() > new Date(endDate).getTime() ||
          time.getTime() < new Date(startDate).getTime()
        );
      },
    };
  } else {
    startDateDisable.value = true;
    formInfo.value.data.startDate = "";
    formInfo.value.data.endDate = "";
  }
}
function changeDate(val) {
  if(val){
    getEndDate(val);
  }else{
    formInfo.value.data.endDate = ""
  }
  
}
function getEndDate(val) {
  getBaseFiscalPeriodEndDate(val).then((res) => {
    if (res && res.success) {
      formInfo.value.data.endDate = res.data
    }
  });
}
function handleClose() {
  formInfo.value.data = {
    initMonth: "",
    startDate: "",
    endDate: "",
  };
  dateInfo.value.visible = false;
  startDateDisable.value = true;
  proxy.$nextTick(() => {
    formInfo.value.ref.clearValidate();
  });
}
function createFiscalPeriod() {
  dateInfo.value.visible = true;
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      creatBaseFiscalPeriod(formInfo.value.data).then((res) => {
        if (res && res.success) {
          getList();
          handleClose();
        }
      });
    }
  });
}
function handleEvent(event, data) {
  switch (event) {
    case "list":
      //存在数据时开启会计期间不可点击
      if (data.length > 0) {
        openInitDisabled.value = true;
      }
      break;
  }
}

async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value);
    }
  });
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true;
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {};
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList];
  advancedSearchInfo.value.data = obj.data;
  await getList();
  clearType.value = !clearType.value;
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(filterInfo.value.copyQueryMap);
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random();
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryDtoList = [];
  tableInfo.value.initCurpage = Math.random();
  tableInfo.value.refresh = Math.random();
}
function clearSearch() {
  clearType.value = !clearType.value;
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
  search();
}
function getCustomize(slipRequest = true) {
  let param = {
    tableKey:
      "baseFiscalPeriodList-com.slip.spd.entity.vo.asset.settings.FiscalPeriodVO",
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      filterInfo.value.query.customizeUserVO = data;
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      );
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      );
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      };
      filterInfo.value.searchList = searchInfo.searchList;
      filterInfo.value.searchList.forEach((item) => {
        item.event = search;
      });
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      );
      slipSelectRequest.value = slipRequest;
      tableInfo.value.api = getBaseFiscalPeriodCustomizeListPage;
      getList();
    }
  });
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr);
    filterInfo.value.sortArr = arr;
    filterInfo.value.query.sortString = arr.length ? arr.toString() : "";
    getList();
  }
}
</script>

<style scoped lang="scss">
.dialogInfo-form-title {
  width: 100%;
  padding-left: 10px;
  color: #6dc1a9;
  margin-bottom: 20px;
  span {
    color: rgb(95, 91, 91);
    font-size: 12px;
  }
}
</style>
